package com.ansion.utils.file;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;

import androidx.core.content.FileProvider;

import com.ansion.log.VLog;
import com.ansion.utils.ResourceUtils;

import java.io.File;

/**
 * created by zhaoyuntao
 * on 2020/7/24
 * description:
 */
public class SFileProvider {
    public static Uri getUriForFile(File file) {
        Uri fileUri = null;
        try {
            if (Build.VERSION.SDK_INT >= 24) {
                fileUri = getUriForFile24(file);
            } else {
                fileUri = Uri.fromFile(file);
            }
        } catch (Throwable e) {
            VLog.e("TAG_FILE", "getUriForFile failed", e);
        }
        return fileUri;
    }

    private static Uri getUriForFile24(File file) {
        return FileProvider.getUriForFile(ResourceUtils.getContext(),
                getFileProviderAuthority(),
                file);
    }

    public static String getFileProviderAuthority() {
        return ResourceUtils.getContext().getPackageName() + ".fileprovider";
    }

    public static void setIntentDataAndType(Intent intent,
                                            String type,
                                            File file,
                                            boolean writeAble) {
        if (Build.VERSION.SDK_INT >= 24) {
            intent.setDataAndType(getUriForFile(file), type);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            if (writeAble) {
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
        } else {
            intent.setDataAndType(Uri.fromFile(file), type);
        }
    }
}
